﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Infrastructure
{
    public static class LibExceptionUtils
    {
        /// <summary>
        /// 获取实际异常.
        /// </summary>
        /// <param name="ex">异常.</param>
        /// <returns>实际异常.</returns>
        public static Exception GetError(Exception ex)
        {
            if (ex == null)
            {
                return null;
            }

            Exception innerError = null;
            GetInnerErrorMsg(ex, ref innerError);
            return innerError ?? ex;
        }

        /// <summary>
        /// 获取内嵌异常.
        /// </summary>
        /// <param name="ex">异常.</param>
        /// <returns>内嵌异常.</returns>
        public static Exception GetInnerError(Exception ex)
        {
            if (ex == null)
            {
                return null;
            }

            Exception innerError = null;
            GetInnerErrorMsg(ex, ref innerError);
            return innerError;
        }

        private static void GetInnerErrorMsg(Exception ex, ref Exception innerException)
        {
            if (ex == null)
            {
                return;
            }

            if (ex.InnerException != null)
            {
                innerException = ex.InnerException;
                GetInnerErrorMsg(ex.InnerException, ref innerException);
            }
        }
    }
}
